<?php

namespace common\components\system;

use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\Url;
use common\helpers\IpHelper;

/**
 * Description of AdminLog
 *
 * @author emhome
 */
abstract class BaseLogRecord extends \yii\base\BaseObject {

    use \yii\base\StaticInstanceTrait;

    public $modelClass;
    public $config = [];

    /**
     * Initializes the object.
     * This method is invoked at the end of the constructor after the object is initialized with the
     * given configuration.
     */
    public function init() {
        if (!$this->modelClass) {
            throw new InvalidConfigException('The "modelClass" configuration for the Application is required.');
        }
    }

    public function getModel() {
        return Yii::createObject($this->modelClass, $this->config);
    }

    public function getRequestData($request = null) {
        if (!$request) {
            $request = Yii::$app->request;
        }
        $headers = $request->getHeaders()->toArray();
        foreach ($headers as $key => $vls) {
            $headers[$key] = $vls[0];
        }
        return [
            'method' => $request->getMethod(),
            'url' => $request->getUrl(),
            'queryParams' => $request->getQueryParams(),
            'bodyParams' => $request->getBodyParams(),
            'headers' => $headers,
            'userAgent' => $request->getUserAgent(),
        ];
    }

    /**
     * @param type $data
     * @param \yii\web\Request|null $request
     */
    public function save($data, $request = null) {
        $model = $this->getModel();
        $model->attributes = [
            'route' => Url::to(),
            'user_id' => Yii::$app->user->id,
            'request' => $this->getRequestData($request),
            'ip' => IpHelper::ip(),
            'ip_server' => IpHelper::getServerIp(),
            'ip_real' => IpHelper::getRealIp(),
            'site' => Yii::$app->id,
        ];
        $model->setAttributes($data);

        if (YII_ENV_DEV && YII_DEBUG) {
            Yii::info([
                $model->attributes
            ], __METHOD__);
        }
        if (YII_ENV_PROD) {
            $model->save(false);
        }
    }

    /**
     * 
     * @param type $data
     * @param \yii\web\Request|null $request
     */
    public static function log($data, $request = null) {
        $model = static::instance();
        $model->save($data, $request);
    }

}
